package com.example.demo.ai.check;

import com.example.demo.ai.sftp.SftpService;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;

@Service
public class CheckService {
    @Autowired
    private SftpService sftpService;

    public String executeRemoteCommand(String imagePath, String pyPath) throws Exception {
        Channel channel = sftpService.createChannel("sftp");
        ChannelSftp sftp = (ChannelSftp) channel;
        if(sftp == null) return null;
        String remoteDir = "/root/yolo-project/checkImage";
        remoteDir = remoteDir.replace("\\", "/");
        try{

            imagePath = uploadFile(sftp, "C:\\Users\\admin\\Desktop\\新建文件夹 (2)\\夏黑3.jpg", remoteDir);
        } catch (Exception e){
            System.out.println("gg");
        } finally {
            sftp.exit();
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }

        OkHttpClient client = new OkHttpClient();
//        String modelPath = "/root/yolo-project/runs/detect/train40/weights/best.pt";
        Request request = new Request.Builder()
                .url("http://10.2.188.107:8000/detect?image_path="+imagePath+"&model_path="+pyPath+"&confidence=0.5")
                .get()
                .build();

        // 发送请求并处理响应
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        JSONObject jsonResponse = new JSONObject(responseBody);
        System.out.println("结果: " + jsonResponse);  // 输出: 25
        return String.valueOf(jsonResponse);
    }

    private String uploadFile(ChannelSftp sftp, String localFile, String remoteDir)
            throws SftpException, IOException {
        File file = new File(localFile);
        String remotePath = remoteDir.replace("\\", "/") + "/" + file.getName();

        try (InputStream is = Files.newInputStream(file.toPath())) {
            sftp.put(is, remotePath);

        } catch (SftpException e) {
            System.err.println("文件上传失败: " + remotePath);
            throw e;
        }
        return remotePath;
    }
}
